import React, { useEffect, useState } from "react";
import { Checkbox, Form, Input, Select } from "antd";
import { QuestionTitlePropsType } from "./interface";

const PropComponent: React.FC<QuestionTitlePropsType> = (
  props: QuestionTitlePropsType
) => {
  const { text, level, isCenter, onChange, disabled } = props;
  const [form] = Form.useForm();
  const [inputValue, setInputValue] = useState("");

  useEffect(() => {
    form.setFieldsValue({ text, level, isCenter });
  }, [text, level, isCenter]);

  function handleValueChange() {
    if (onChange) onChange(form.getFieldsValue());
  }

  function handleBlur() {
    const currentValue = form.getFieldValue("text");

    if (currentValue !== "") return;
    form.setFieldValue("text", inputValue);
    if (onChange) onChange(form.getFieldsValue());
    form.resetFields();
  }

  return (
    <Form
      layout="vertical"
      initialValues={{ text, level, isCenter }}
      form={form}
      onValuesChange={handleValueChange}
      disabled={disabled}
    >
      <Form.Item
        label="内容"
        name="text"
        rules={[{ required: true, message: "请输入内容" }]}
      >
        <Input
          onFocus={(e) => setInputValue(e.target.value)}
          onBlur={handleBlur}
          allowClear
        />
      </Form.Item>
      <Form.Item label="层级" name="level">
        <Select
          options={[
            {
              label: 1,
              value: 1,
            },
            {
              label: 2,
              value: 2,
            },
            {
              label: 3,
              value: 3,
            },
            {
              label: 4,
              value: 4,
            },
            {
              label: 5,
              value: 5,
            },
          ]}
        />
      </Form.Item>
      <Form.Item name="isCenter" valuePropName="checked">
        <Checkbox>居中显示</Checkbox>
      </Form.Item>
    </Form>
  );
};

export default PropComponent;
